import re
import reprlib

# 之前的版本 用words存储所有word 浪费内存
RE_WORDS = re.compile('\w+')


class Sentence:

    def __init__(self, text):
        self.text = text

    def __repr__(self):
        return 'Sentence(%s)' % reprlib.repr(self.text)

    def __iter__(self):
        for match in RE_WORDS.finditer(self.text):
            # 按需返回re.MatchObject实例
            yield match.group()


if __name__ == '__main__':
    s = Sentence('"The time has come," the Walrus said,')
    print(s)
    for word in s:
        print(word)
    print(list(s))
    s3 = Sentence('Pig and Pepper')
    it = iter(s3)
    print(it)
    print(next(it))
    print(next(it))
    print(next(it))
    print(list(it))
    print(list(iter(s3)))
